package de.lazy.gui.filebuffer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class FileBufferSerializer implements FileBufferOperator {

	private File bufferFile;
	
	public FileBufferSerializer(String bufferFile) {
		this.bufferFile = new File(bufferFile);
	}


	@Override
	public FileBufferObject read() throws IOException {
		if(bufferFile == null || !bufferFile.canRead()){
			throw new IOException("Buffer file is null!");
		}
		
		ObjectInput inputStream = null;
		FileBufferObject bufferObject = null;
		//class not found exception abfangen
		try{
			inputStream = new ObjectInputStream(new FileInputStream(bufferFile));
			bufferObject =  (FileBufferObject) inputStream.readObject();
		}
		catch(FileNotFoundException e){
			System.err.println(bufferFile.getAbsolutePath()+" is empty, using empty list");
		}
		catch(ClassNotFoundException e){
			throw new IOException(e);
		}
		catch(Exception e){
			throw e;
		}
		finally{
			if(inputStream != null){
				inputStream.close();
			}
			
		}
		
		if(bufferObject == null){
			bufferObject = new FileBufferObject();
		}
		return bufferObject;
	}
	

	@Override
	public void write(FileBufferObject o) throws IOException {
		if(bufferFile == null){
			throw new FileNotFoundException("Buffer file is null!");
		}
		ObjectOutput outputStream = null;
		
		try{
			outputStream = new ObjectOutputStream(new FileOutputStream(bufferFile));
			outputStream.writeObject(o);
		}
		catch(Exception e){
			throw e;
		}
		finally {
			outputStream.close();
		}
	}

}
